package top.codedance.iotp.common.util;

import org.apache.log4j.Logger;

import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

/**
 * 生成公钥和私钥
 */
public class RSAEncrypt implements AEncryption {
    private static Logger logger = Logger.getLogger(RSAEncrypt.class);

    private static final String ENCRYPT_TYPE = "RSA"; //RSA  PKCS8
    private final static String KEY_RSA_SIGNATURE = "MD5withRSA";
    // RSA最大加密明文大小
    private static final int MAX_ENCRYPT_BLOCK = 117;
    // RSA最大解密密文大小
    private static final int MAX_DECRYPT_BLOCK = 128;

    /**
     * 随机生成密钥对
     *
     * @throws Exception
     */
    @Override
    public AsymmetricEncryption.KeyStringPair genKeyPair() throws Exception {
        // KeyPairGenerator类用于生成公钥和私钥对，基于RSA算法生成对象
        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(ENCRYPT_TYPE);
        // 初始化密钥对生成器，密钥大小为96-1024位
        keyPairGen.initialize(1024, new SecureRandom());
        // 生成一个密钥对，保存在keyPair中
        KeyPair keyPair = keyPairGen.generateKeyPair();
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();   // 得到私钥
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();  // 得到公钥
        String publicKeyString = new String(Base64or32Tool.encode(publicKey.getEncoded()), StandardCharsets.UTF_8);
        // 得到私钥字符串
        String privateKeyString = new String(Base64or32Tool.encode(privateKey.getEncoded()), StandardCharsets.UTF_8);
        logger.debug("----------------------公钥串start------------------------------");
        logger.debug(publicKeyString);
        logger.debug("-------------------------公钥串end---------------------------");
        logger.debug("-------------------------私钥串start---------------------------");
        logger.debug(privateKeyString);
        logger.debug("-------------------------私钥串end---------------------------");
        // 返回公钥和私钥对
        return new AsymmetricEncryption.KeyStringPair(privateKeyString, publicKeyString);
    }

    /**
     * RSA公钥加密
     *
     * @param body      加密字符串
     * @param publicKey 公钥
     * @return 密文
     * @throws Exception 加密过程中的异常信息
     */
    @Override
    public String encrypt(byte[] body, String publicKey) throws Exception {
        //base64编码的公钥
        byte[] decoded = Base64or32Tool.decode(publicKey.getBytes(StandardCharsets.UTF_8));
        RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance(ENCRYPT_TYPE).generatePublic(new X509EncodedKeySpec(decoded));
        //RSA加密
        Cipher cipher = Cipher.getInstance(ENCRYPT_TYPE);
        cipher.init(Cipher.ENCRYPT_MODE, pubKey);
        byte[] enBytes = null;
        // 返回加密后由Base64编码的加密信息
        int inputLen = body.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;
        byte[] cache;
        int i = 0;
        // 对数据分段加密
        while (inputLen - offSet > 0) {
            if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
                cache = cipher.doFinal(body, offSet, MAX_ENCRYPT_BLOCK);
            } else {
                cache = cipher.doFinal(body, offSet, inputLen - offSet);
            }
            out.write(cache, 0, cache.length);
            i++;
            offSet = i * MAX_ENCRYPT_BLOCK;
        }
        enBytes = out.toByteArray();
        out.close();
        String outStr = new String(Base64or32Tool.encode(enBytes), StandardCharsets.UTF_8);
        return outStr;
    }

    /**
     * RSA公钥加密
     *
     * @param body      加密字符串
     * @param publicKey 公钥
     * @return 密文
     * @throws Exception 加密过程中的异常信息
     */
    @Override
    public String encrypt(String body, String publicKey) throws Exception {
        byte[] data = body.getBytes(StandardCharsets.UTF_8);
        return encrypt(data, publicKey);
    }

    /**
     * RSA私钥解密
     *
     * @param body       加密字符串
     * @param privateKey 私钥
     * @return 铭文
     * @throws Exception 解密过程中的异常信息
     */
    @Override
    public String decrypt(byte[] body, String privateKey) throws Exception {
        //64位解码加密后的字符串
        byte[] inputByte = Base64or32Tool.decode(body);
        //base64编码的私钥
        byte[] decoded = Base64or32Tool.decode(privateKey.getBytes(StandardCharsets.UTF_8));
        RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance(ENCRYPT_TYPE).generatePrivate(new PKCS8EncodedKeySpec(decoded));
        //RSA解密
        Cipher cipher = Cipher.getInstance(ENCRYPT_TYPE);
        cipher.init(Cipher.DECRYPT_MODE, priKey);
        StringBuilder sb = new StringBuilder();
        // 返回UTF-8编码的解密信息
        int inputLen = inputByte.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;
        byte[] cache;
        int i = 0;
        // 对数据分段解密
        while (inputLen - offSet > 0) {
            if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
                cache = cipher.doFinal(inputByte, offSet, MAX_DECRYPT_BLOCK);
            } else {
                cache = cipher.doFinal(inputByte, offSet, inputLen - offSet);
            }
            out.write(cache, 0, cache.length);
            i++;
            offSet = i * MAX_DECRYPT_BLOCK;
        }
        sb.append(new String(out.toByteArray(), StandardCharsets.UTF_8));
        out.close();
        String outStr = sb.toString();
        return outStr;
    }

    /**
     * RSA私钥解密
     *
     * @param body       加密字符串
     * @param privateKey 私钥
     * @return 铭文
     * @throws Exception 解密过程中的异常信息
     */
    @Override
    public String decrypt(String body, String privateKey) throws Exception {
        return decrypt(body.getBytes(StandardCharsets.UTF_8), privateKey);
    }

    /**
     * 用私钥对加密数据进行签名
     *
     * @param encryptedStr
     * @param privateKey
     * @return
     */
    @Override
    public String sign(String encryptedStr, String privateKey) {
        String str = "";
        try {
            //将私钥加密数据字符串转换为字节数组
            byte[] data = encryptedStr.getBytes(StandardCharsets.UTF_8);
            // 解密由base64编码的私钥
            byte[] bytes = Base64or32Tool.decode(privateKey.getBytes());
            // 构造PKCS8EncodedKeySpec对象
            PKCS8EncodedKeySpec pkcs = new PKCS8EncodedKeySpec(bytes);
            // 指定的加密算法
            KeyFactory factory = KeyFactory.getInstance(ENCRYPT_TYPE);
            // 取私钥对象
            PrivateKey key = factory.generatePrivate(pkcs);
            // 用私钥对信息生成数字签名
            Signature signature = Signature.getInstance(KEY_RSA_SIGNATURE);
            signature.initSign(key);
            signature.update(data);
            str = new String(Base64or32Tool.encode(signature.sign()), StandardCharsets.UTF_8);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return str;
    }

    /**
     * 校验数字签名
     *
     * @param body
     * @param publicKey
     * @param sign
     * @return 校验成功返回true，失败返回false
     */
    @Override
    public boolean verify(String body, String publicKey, String sign) {
        boolean flag = false;
        try {
            //将私钥加密数据字符串转换为字节数组
            byte[] data = body.getBytes(StandardCharsets.UTF_8);
            // 解密由base64编码的公钥
            byte[] bytes = Base64or32Tool.decode(publicKey.getBytes());
            // 构造X509EncodedKeySpec对象
            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(bytes);
            // 指定的加密算法
            KeyFactory factory = KeyFactory.getInstance(ENCRYPT_TYPE);
            // 取公钥对象
            PublicKey key = factory.generatePublic(keySpec);
            // 用公钥验证数字签名
            Signature signature = Signature.getInstance(KEY_RSA_SIGNATURE);
            signature.initVerify(key);
            signature.update(data);
            flag = signature.verify(Base64or32Tool.decode(sign.getBytes(StandardCharsets.UTF_8)));
        } catch (Exception e) {
            logger.debug(e.getMessage());
        }
        return flag;
    }
}
